package com.yakami.ocean.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.squareup.picasso.Picasso;
import com.trello.rxlifecycle.ActivityEvent;
import com.yakami.ocean.AppManager;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.adapter.DialogClassifyAdapter;
import com.yakami.ocean.adapter.DialogPaperAdapter;
import com.yakami.ocean.bean.Classify;
import com.yakami.ocean.bean.ListContainer;
import com.yakami.ocean.bean.News;
import com.yakami.ocean.bean.TestPaperProfile;
import com.yakami.ocean.bean.UserInfo;
import com.yakami.ocean.event.Event;
import com.yakami.ocean.event.RxBus;
import com.yakami.ocean.utils.IntentHelper;
import com.yakami.ocean.utils.Tools;
import com.yakami.ocean.view.activity.base.BaseTransparentTabsActivity;
import com.yakami.ocean.view.fragment.NestedNewsListFragment;
import com.yakami.ocean.view.fragment.TextListDialogFragment;
import com.yakami.ocean.view.fragment.UserInfoFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/12
 */
public class MainActivity extends BaseTransparentTabsActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Bind(R.id.nav_view) NavigationView mNavView;
    @Bind(R.id.drawer_layout) DrawerLayout mDrawer;
    @Bind(R.id.scroller) NestedScrollView mScroller;
    @Bind(R.id.btn_branch) RelativeLayout mBtnBranch;
    @Bind(R.id.btn_user) RelativeLayout mBtnPopular;
    @Bind(R.id.btn_test) RelativeLayout mBtnTest;
    @Bind(R.id.btn_search) RelativeLayout mBtnSearch;
    @Bind(R.id.recommend_list) LinearLayout mRecommendView;
    @Bind(R.id.latest_list) LinearLayout mLatestView;
    @Bind(R.id.quality_list) LinearLayout mQualityView;

    private LinearLayout mUserInfoLayout;
    private CircleImageView mPortraitView;
    private ImageView mLogout;
    private TextView mUserName;
    //test
    //test
    //test
    //test
    //test
    //Test
    //Test

    private List<NestedNewsListFragment> mFragmentList;
    private boolean mIsBacking;
    private Toast mBackingToast;
    private int mScrollY; //用于记录scrollView的滑动位置，避免5.0+上透明状态栏+drawLayout导致的scrollView在drawLayout关闭时自动滑动。
    private boolean mCanScroll = true; //scroller是否能滑动

    @Override
    protected void onCreate(Bundle savedInstanceBundle) {
        super.onCreate(savedInstanceBundle);

        mTitle.setText(mRes.getText(R.string.app_name));

        //设定滑动toolbar、status bar的透明度效果
        mScroller.setOnScrollChangeListener((NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
                    //避免自动滑动bug
                    if (!mCanScroll) {
                        mScroller.setScrollY(mScrollY);
                        return;
                    }
                    scrollY = scrollY / 2;
                    //为了避免drawables间共享状态导致锁状态问题，得先使用mutate()进行变种处理te
                    mToolbar.getBackground().mutate().setAlpha(scrollY > 255 ? 255 : scrollY);
                    mStatusBarBg.getBackground().mutate().setAlpha(scrollY > 255 ? 255 : scrollY);
                }
        );
        //初始化scrollView为顶部
        mScroller.post(() -> mScroller.setScrollY(0));

        initDrawer();

        initTabs(savedInstanceBundle != null);

        initNavBar();

        initSubscriber();
        setLogin(true);
    }

    private int add(int a, int b) {
        return a + b;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 初始化侧滑栏
     */
    protected void initDrawer() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawer.addDrawerListener(toggle);
        toggle.syncState();
        mNavView.setNavigationItemSelectedListener(this);
        mUserInfoLayout = (LinearLayout) mNavView.getHeaderView(0).findViewById(R.id.user_area);
        mPortraitView = (CircleImageView) mNavView.getHeaderView(0).findViewById(R.id.portrait);
        mUserName = (TextView) mNavView.getHeaderView(0).findViewById(R.id.user_name);
        mLogout = (ImageView) mNavView.getHeaderView(0).findViewById(R.id.logout);
        RxView.clicks(mUserInfoLayout)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    if (AppManager.mUser == null)
                        startActivity(new Intent(mContext, LoginActivity.class));
                });
        RxView.clicks(mLogout)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    RxBus.getInstance().send(Event.EventType.OUT_LOGIN, null);
                });
        //添加drawerLayout监听，修补drawLayout关闭时scrollView自动滑动bug
        mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                mScrollY = mScroller.getScrollY();
                mCanScroll = false;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mCanScroll = true;
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
    }

    /**
     * 初始化4个导航按钮
     */
    protected void initNavBar() {
        //btn分类资源
        RxView.clicks(mBtnBranch)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Void) -> {
                    TextListDialogFragment dialog = new TextListDialogFragment();
                    dialog.setAdapter(new DialogClassifyAdapter(mAppContext));
                    dialog.setTitle(mRes.getText(R.string.ic_classify).toString());
                    dialog.setOnRefreshListener(() -> {
                        ServerAPI.getOceanAPI()
                                .getTypeTree()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(container -> {
                                    dialog.setData(container.list);
                                    dialog.onSuccess();
                                }, throwable -> {
                                    throwable.printStackTrace();
                                    dialog.onError();
                                });
                    });
                    dialog.setOnItemClickListener((pos, data) -> {
                        startActivity(IntentHelper.newInstance(mContext, ClassifyActivity.class)
                                .putSerializable("data", (Classify) data)
                                .toIntent());
                    });
                    dialog.show(getSupportFragmentManager(), "LIST_DIALOG");
                });

        //btn科普活动
        RxView.clicks(mBtnPopular)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Void) -> {
                    startActivity(new Intent(mContext, PopularActivity.class));
                });

        //btn在线测试
        RxView.clicks(mBtnTest)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Void) -> {
                    if (AppManager.mUser == null) {
                        Tools.toast(AppManager.context, mRes.getString(R.string.please_login_first));
                        return;
                    }
                    TextListDialogFragment dialog = new TextListDialogFragment();
                    dialog.setAdapter(new DialogPaperAdapter(mAppContext));
                    dialog.setTitle(mRes.getText(R.string.ic_test).toString());
                    dialog.setOnRefreshListener(() -> {
                        ServerAPI.getOceanAPI()
                                .getTestPaperList()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(container -> {
                                    dialog.setData(container.list);
                                    dialog.onSuccess();
                                }, throwable -> {
                                    throwable.printStackTrace();
                                    dialog.onError();
                                });
                    });
                    dialog.setOnItemClickListener((pos, data) -> {
                        startActivity(IntentHelper.newInstance(mContext, TestActivity.class)
                                .putInt("id", ((TestPaperProfile) data).id)
                                .putString("name", ((TestPaperProfile) data).name)
                                .toIntent());
                    });
                    dialog.show(getSupportFragmentManager(), "TEST_PAPER_DIALOG");
                });

        //btn搜索资源
        RxView.clicks(mBtnSearch)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Void) -> {
                    Intent intent = new Intent(mContext, SearchActivity.class);
                    startActivity(intent);
                });
    }

    /**
     * 初始化消息订阅者
     */
    protected void initSubscriber() {
        //登录
        RxBus.with(this)
                .setEvent(Event.EventType.LOGIN_SUCCESS)
                .setEndEvent(ActivityEvent.DESTROY)
                .onNext(event -> {
                    setLogin(false);
                }).create();
        //退出登录
        RxBus.with(this)
                .setEvent(Event.EventType.OUT_LOGIN)
                .setEndEvent(ActivityEvent.DESTROY)
                .onNext(event -> {
                    onBackPressed();
                    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    dialog.setTitle("是否退出登录？");
                    dialog.setCancelable(true);
                    dialog.setPositiveButton(mRes.getString(R.string.ok), (dialogInstance, which) -> {
                        AppManager.logout();
                        setLogin(false);
                    });
                    dialog.setNegativeButton(mRes.getString(R.string.no), (dialogInstance, which) -> {
                    });
                    dialog.show();
                }).create();
    }

    protected void setLogin(boolean isInit) {
        //初始化
        if (isInit) {
            //从缓存中加载用户信息
            UserInfo user = AppManager.getLocalUser();
            if (user != null) {
                Picasso.with(mAppContext).load(ServerAPI.getUploadsUrl(user.portraitUrl)).into(mPortraitView);
                mUserName.setText(user.name);
                mLogout.setVisibility(View.VISIBLE);
            } else
                mPortraitView.setColorFilter(mRes.getColor(R.color.white));
            ServerAPI.getOceanAPI()
                    .getUserInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(userInfo -> {
                        if (userInfo.isLogined) {
                            Picasso.with(mAppContext).load(ServerAPI.getUploadsUrl(userInfo.portraitUrl)).into(mPortraitView);
                            mUserName.setText(userInfo.name);
                            AppManager.mUser = userInfo;
                            mLogout.setVisibility(View.VISIBLE);
                        } else {
                            //TODO: 无法正常在此种情况下切换图片
                            mPortraitView.post(() -> {
                                mPortraitView.setImageResource(R.drawable.ic_account_circle_black_48dp);
                                mPortraitView.setImageDrawable(mRes.getDrawable(R.drawable.ic_account_circle_black_48dp));
                                mPortraitView.setColorFilter(mRes.getColor(R.color.white));
                            });
                            mUserName.setText(mRes.getString(R.string.not_logged));
                            mLogout.setVisibility(View.GONE);
                            AppManager.logout();
                        }
                    }, Throwable::printStackTrace);
        } else { //登录后
            if (AppManager.mUser != null) {
                Picasso.with(mAppContext).load(ServerAPI.getUploadsUrl(AppManager.mUser.portraitUrl)).into(mPortraitView);
                mPortraitView.clearColorFilter();
                mUserName.setText(AppManager.mUser.name);
                mLogout.setVisibility(View.VISIBLE);
            } else {
                mPortraitView.setImageResource(R.drawable.ic_account_circle_black_48dp);
                mPortraitView.setColorFilter(mRes.getColor(R.color.white));
                mUserName.setText(mRes.getString(R.string.not_logged));
                mLogout.setVisibility(View.GONE);
            }
        }
    }


    @Override
    protected void initTabs(boolean isRestarted) {
        super.initTabs(isRestarted);
        List<NestedNewsListFragment>  fragmentList = new ArrayList<>();
        fragmentList.add(new NestedNewsListFragment());
        fragmentList.add(new NestedNewsListFragment());
        fragmentList.add(new NestedNewsListFragment());
        String[] typeArray = {"recommend", "latest", "quality"};
        LinearLayout[] layoutArray = {mRecommendView, mLatestView, mQualityView};
        Event.EventType[] eventArray = {Event.EventType.SET_RECOMMEND_HEIGHT,
                Event.EventType.SET_LATEST_HEIGHT, Event.EventType.SET_QUALITY_HEIGHT};
        int[] layoutIdArray = {R.id.recommend_list, R.id.latest_list, R.id.quality_list};
        for (int i = 0; i < fragmentList.size(); i++) {
            final int num = i;
            NestedNewsListFragment fragment = fragmentList.get(num);
            fragment.setReturnedEventType(eventArray[num]);
            fragment.setRefreshListener(() -> {
                        fragment.onLoading();
                        ServerAPI.getOceanAPI().getHomeDataByType(typeArray[num])
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe((ListContainer<News> newsList) -> {
                                            //必须预先设置layout的高度，否则items无法显示
                                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutArray[num].getLayoutParams();
                                            params.height = 10000;
                                            layoutArray[num].setLayoutParams(params);
                                            RxBus.with(MainActivity.this)
                                                    .setEvent(eventArray[num])
                                                    .setEndEvent(ActivityEvent.DESTROY)
                                                    .onNext((Event<?> event) -> {
                                                        params.height = event.getMessage();
                                                        layoutArray[num].setLayoutParams(params);
                                                    }).create();
                                            fragment.setData(newsList.list);
                                            fragment.onSuccess();
                                        }, (Throwable throwable) -> {
                                            throwable.printStackTrace();
                                            fragment.onError();
                                        }
                                );

                    }
            );

            fragment.setOnItemClickListener((pos, data) -> {
                startActivity(IntentHelper.newInstance(mContext, DetailActivity.class)
                        .putSerializable("data", (News) data)
                        .toIntent());
            });

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_out_left);
            transaction.replace(layoutIdArray[num], fragment, typeArray[num]).commit();
        }
    }

    @Override
    protected int onBindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (mIsBacking) {
                if (mBackingToast != null)
                    mBackingToast.cancel();
                android.os.Process.killProcess(android.os.Process.myPid());
            } else {
                mIsBacking = true;
                mBackingToast = Toast.makeText(this, mRes.getString(R.string.click_again_to_exit), Toast.LENGTH_LONG);
                mBackingToast.show();
                new Handler().postDelayed(() -> {
                    mIsBacking = false;
                    if (mBackingToast != null)
                        mBackingToast.cancel();
                }, 2000);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_about) {
            startActivity(IntentHelper.newInstance(mContext, AboutActivity.class).toIntent());
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("all")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id) {
            case R.id.nav_user_info:
                if (AppManager.mUser != null)
                    startActivity(IntentHelper.newInstance(mContext, SingleLoadFragmentActivity.class)
                            .putString("class", UserInfoFragment.class.toString())
                            .putString("title", mRes.getString(R.string.user_info))
                            .toIntent());
                else
                    Tools.toast(AppManager.context, mRes.getString(R.string.please_login_first));
                break;

            case R.id.nav_collection_list:
                if (AppManager.mUser != null)
                    startActivity(IntentHelper.newInstance(mContext, CollectionActivity.class).toIntent());
                else
                    Tools.toast(AppManager.context, mRes.getString(R.string.please_login_first));
                break;

            case R.id.nav_test_record:
                if (AppManager.mUser != null)
                    startActivity(IntentHelper.newInstance(mContext, TestRecordActivity.class).toIntent());
                else
                    Tools.toast(AppManager.context, mRes.getString(R.string.please_login_first));
                break;

            case R.id.nav_about:
                startActivity(IntentHelper.newInstance(mContext, AboutActivity.class).toIntent());
                break;

            case R.id.nav_share:
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "海洋气象科普在线");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "海洋气象科普在线Android客户端！下载链接：http://112.74.204.89/app/ocean.apk");
                shareIntent.setType("text/plain");
                shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

                //设置分享列表的标题，并且每次都显示分享列表
                startActivity(Intent.createChooser(shareIntent, "分享到"));
                break;
        }
        //关闭侧边栏
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
